package com.glp.work.flow.controller;

import com.github.pagehelper.PageInfo;
import com.glp.common.enums.ReturnEnum;
import com.glp.common.reponse.BaseResponse;
import com.glp.common.reponse.BaseResult;
import com.glp.oss.client.SimpleOssClient;
import com.glp.work.flow.constant.APICode;
import com.glp.work.flow.constant.Constants;
import com.glp.work.flow.constant.Keys;
import com.glp.work.flow.exception.APIException;
import com.glp.work.flow.inteface.InsertCheck;
import com.glp.work.flow.inteface.UpdateCheck;
import com.glp.work.flow.mapper.WfTaskAssignMapper;
import com.glp.work.flow.pojo.WfForm;
import com.glp.work.flow.pojo.WfTaskAssign;
import com.glp.work.flow.request.WfFormDTO;
import com.glp.work.flow.request.WfOrderQueryDTO;
import com.glp.work.flow.response.PageInfoResponse;
import com.glp.work.flow.response.WfOrderResultDTO;
import com.glp.work.flow.service.UserTaskAssignService;
import com.glp.work.flow.service.WfFormService;
import com.glp.work.flow.service.WfPlatformDefService;
import com.glp.work.flow.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 表单管理Controller
 *
 * @author jhuang1
 */
@Api(tags = {"表单管理Controller"})
@Slf4j
@RequestMapping("/form")
@RestController
public class WfFormController {

    @Resource
    private WfFormService wfFormService;
    @Resource
    private SimpleOssClient simpleOssClient;
    @Resource
    private WfTaskAssignMapper wfTaskAssignMapper;
    @Resource
    private WfPlatformDefService wfPlatformDefService;

    /**
     * 新增表单
     *
     * @param wfFormDTO 表单对象
     * @return WfFormDTO
     */
    @ApiOperation(value = "表单模板查询接口")
    @GetMapping(value = "/queryFormList")
    public BaseResult queryFormList(WfFormDTO wfFormDTO) {
        try {
            log.info("表单模板查询接口,请求参数:{}", wfFormDTO);
            PageInfo<WfFormDTO> pageInfoDTO = wfFormService.queryFormList(wfFormDTO);
            BaseResult baseResult = BaseResponse.success(pageInfoDTO);
            log.info("表单模板查询接口,响应结果:{}", baseResult);
            return baseResult;
        } catch (APIException e) {
            log.error("表单模板查询接口,APIException", e);
            return e.parse();
        } catch (Exception e) {
            log.error("表单模板查询接口,Exception", e);
            return BaseResponse.error(ReturnEnum.ERROR);
        }
    }

    /**
     * 新增表单
     *
     * @param wfFormDTO 表单对象
     * @return WfFormDTO
     */
    @PostMapping(value = "/insertForm")
    @ApiOperation(value = "新增表单模板接口")
    public BaseResult insertForm(@RequestBody @Validated({InsertCheck.class}) WfFormDTO wfFormDTO,
                                 @RequestHeader(value = Keys.USERNO) String userNo) {
        try {
            log.info("新增表单,请求参数:{}", wfFormDTO);
            WfForm wfForm = new WfForm();
            BeanUtils.copyProperties(wfFormDTO, wfForm);
            wfForm.setCreateUser(userNo);
            wfFormService.insertForm(wfForm);
            BeanUtils.copyProperties(wfForm, wfFormDTO);
            BaseResult baseResult = BaseResponse.success(wfFormDTO);
            log.info("新增表单,响应结果:{}", baseResult);
            return baseResult;
        } catch (APIException e) {
            log.error("新增表单,APIException", e);
            return e.parse();
        } catch (Exception e) {
            log.error("新增表单,Exception", e);
            return BaseResponse.error(ReturnEnum.ERROR);
        }
    }

    /**
     * 修改表单
     *
     * @param wfFormDTO 表单对象
     * @return WfFormDTO
     */
    @ApiOperation(value = "修改表单模板接口")
    @PostMapping(value = "/updateForm")
    public BaseResult updateForm(@RequestBody @Validated({UpdateCheck.class}) WfFormDTO wfFormDTO,
                                 @RequestHeader(value = Keys.USERNO) String userNo) {
        try {
            Example example = new Example(WfTaskAssign.class);
            example.createCriteria().andEqualTo("taskDefForm",wfFormDTO.getFormCode());
            log.info("修改表单,请求参数:{}", wfFormDTO);
            WfForm wfForm = new WfForm();
            BeanUtils.copyProperties(wfFormDTO, wfForm);
            wfForm.setUpdateUser(userNo);
            wfForm.setUpdateTime(DateUtils.getCurrent());
            wfForm.setStatus("0");
            wfFormService.updateForm(wfForm);
            BeanUtils.copyProperties(wfForm, wfFormDTO);
            BaseResult baseResult = BaseResponse.success(wfFormDTO);
            log.info("修改表单,响应结果:{}", baseResult);
            return baseResult;
        } catch (APIException e) {
            log.error("修改表单,APIException", e);
            return e.parse();
        } catch (Exception e) {
            log.error("修改表单,Exception", e);
            return BaseResponse.error(ReturnEnum.ERROR);
        }
    }

    /**
     * 表单模板启用/禁用接口
     *
     * @param id     表单ID
     * @param status 表单状态
     * @return status
     */
    @ApiOperation(value = "表单模板启用/禁用接口")
    @GetMapping(value = "/updateFormStatus")
    public BaseResult updateFormStatus(@RequestParam Long id, @RequestParam String status,
                                       @RequestHeader(value = Keys.USERNO) String userNo) {
        try {
            log.info("修改状态,请求参数,id:{},status:{}", id, status);
            if (null == id || StringUtils.isBlank(status)) {
                throw new APIException(APICode.NULL_PARAMETER);
            }
            if (!Constants.STATUS_1.equals(status) && !Constants.STATUS_0.equals(status)) {
                throw new APIException(APICode.INVALID_PARAMETER);
            }
            WfForm wfForm = new WfForm();
            wfForm.setId(id);
            wfForm.setStatus(status);
            wfForm.setUpdateUser(userNo);
            wfFormService.updateFormStatus(wfForm);
            BaseResult baseResult = BaseResponse.success();
            log.info("修改表单,响应结果:{}", baseResult);
            return baseResult;
        } catch (APIException e) {
            log.error("修改表单,APIException", e);
            return e.parse();
        } catch (Exception e) {
            log.error("修改表单,Exception", e);
            return BaseResponse.error(ReturnEnum.ERROR);
        }
    }

    /**
     * 查询表单明细
     *
     * @param id 表单ID
     * @return status
     */
    @ApiOperation(value = "查询表单明细接口")
    @GetMapping(value = "/queryFormDetail")
    public BaseResult queryFormDetail(@RequestParam Long id) {
        try {
            log.info("查询表单明细,请求参数,id:{}", id);
            if (null == id) {
                throw new APIException(APICode.NULL_PARAMETER);
            }
            WfForm wfForm = wfFormService.queryFormDetail(id);
            WfFormDTO wfFormDTO = new WfFormDTO();
            if (null != wfForm) {
                BeanUtils.copyProperties(wfForm, wfFormDTO);
            }
            BaseResult baseResult = BaseResponse.success(wfFormDTO);
            log.info("修改表单,响应结果:{}", baseResult);
            return baseResult;
        } catch (APIException e) {
            log.error("修改表单,APIException", e);
            return e.parse();
        } catch (Exception e) {
            log.error("修改表单,Exception", e);
            return BaseResponse.error(ReturnEnum.ERROR);
        }
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/uploadFile")
    public Map<String, String> uploadFile(@RequestParam(value = "file") MultipartFile file,
                                          HttpServletResponse response) throws IOException {
        Map<String, String> map = new HashMap<>();
        try {
            if (null == file) {
                throw new APIException(APICode.NOT_FOUND, "请选择上传的文件");
            }
            log.info("文件上传接口，fileName:{},size:{}", file.getOriginalFilename(), file.getSize());
            //生成uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String key = uuid + file.getOriginalFilename();
            String ossUrl = simpleOssClient.uploadFile(key, file.getInputStream());
            log.info("文件上传接口,上传结果：{}", ossUrl);
            //因动态表单空间对返回的格式有要求，不然解析不了URL，故不采用BaseResult返回
            map.put("url", ossUrl);
            return map;
        } catch (Exception e) {
            log.error("upload File Exception:", e);
            response.sendError(APICode.ERROR.getCode(), APICode.ERROR.getMessage());
            return null;
        }
    }
}
